package ro.msg.quiz.service;

import ro.msg.quiz.domain.Quiz;
import ro.msg.quiz.exception.MyException;
import ro.msg.quiz.repository.Repository;
import ro.msg.quiz.validator.IValidator;
import ro.msg.quiz.validator.QuizValidator;

//AUTHORS: Elod, Razvan

//Class responsible for adding, deleting and updating a valid quiz in the list of quizzes from repository
public class QuizService implements IService<Quiz> {
    Repository repo = Repository.getInstance();
    IValidator<Quiz> validator = new QuizValidator();

    // adds a valid quiz in the list of quizzes from repository
    @Override
    public void add(Quiz t) throws MyException {
	if (exists(t))
	    throw new MyException("The quiz already exists!");
	int newId = idGenerator();
	t.setId(newId);
	validator.validate(t);
	repo.getQuizzesList().add(t);
    }

    // deletes a quiz from the list of quizzes from repository
    // if the quiz is not found by it's name than an exception is thrown
    @Override
    public void delete(String quizName) throws MyException {
	for (Quiz q : this.repo.getQuizzesList()) {
	    if (q.getName().equals(quizName)) {
		this.repo.getQuizzesList().remove(q);
		return;
	    }
	}
	throw new MyException("The quiz does not exist!");
    }

    //updates a quiz in the list of quizzes from repository
    //if the quiz exists in repository
    @Override
    public void update(Quiz t) throws MyException {
	if (!exists(t))
	    throw new MyException("The question does not exist!");
	for (Quiz q : repo.getQuizzesList()) {
	    if (q.getId() == t.getId()) {
		t.setName(q.getName());
		t.setQuestionList(q.getQuestionList());
		validator.validate(t);
		repo.getQuizzesList().add(t);
	    }
	}
    }

    // verifies if a quiz appears in repository
    @Override
    public boolean exists(Quiz t) {
	return repo.getQuizzesList().contains(t);
    }

    // generates a new id for a quiz, by incrementing the maximum value of id
    // from the list of quizzes in repository
    @Override
    public int idGenerator() {
	int max = 0;
	for (Quiz q : repo.getQuizzesList()) {
	    if (q.getId() > max) {
		max = q.getId();
	    }
	}
	max++;
	return max;
    }

}
